package com.situ.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.situ.web.entity.User;

public class LoginFilter implements Filter{

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("LoginFilter.doFilter()");
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		
		String uri = httpServletRequest.getRequestURI();
		StringBuffer url = httpServletRequest.getRequestURL();
		String servletPath = httpServletRequest.getServletPath();
		System.out.println(uri);// /JavaWeb1907/login.jsp
		System.out.println(url);// http://localhost:8080/JavaWeb1907/login.jsp
		System.out.println(servletPath);// /login.jsp
		// 如果拦截的是：login.jsp  loginServlet?method=xxx
		// 对于要完成登录的请求都要放行
		if ("/login.jsp".equals(servletPath)
				|| "/checkImg".equals(servletPath)
				|| "/user".equals(servletPath)
				||"/index.jsp".equals(servletPath)
				||"/user_insert.jsp".equals(servletPath)
				||"/banji".equals(servletPath)
				|| servletPath.endsWith(".css")
				|| servletPath.endsWith(".js")
				|| servletPath.endsWith(".jpg")
				|| servletPath.endsWith(".png")
				) {
			chain.doFilter(request, response);
			return;	
		}
			
		
		HttpSession session = httpServletRequest.getSession();
		User user = (User) session.getAttribute("user");
		// 我必须登录上我才能到登录界面
		if (null == user) {
			// 用户没有登录，重定向登录界面
			httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/login.jsp");
			return;
		}
		
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		
	}

}
